package com.zzl.alligator.framework.aspectj.mybatis;

import cn.hutool.core.bean.BeanUtil;
import com.zzl.alligator.common.util.SecurityUtils;
import com.zzl.alligator.framework.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Properties;

/**
 * TODO
 *
 * @author zhouziliang
 * @since 2020/7/3
 */
@Intercepts(
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
)
@Slf4j
public class MateInfoInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        SqlCommandType sqlCommandType = SqlCommandType.INSERT;
        for(Object arg : args) {
            if(arg instanceof MappedStatement) {
                MappedStatement ms = (MappedStatement)arg;
                sqlCommandType = ms.getSqlCommandType();
                log.debug("当前操作类型{}", sqlCommandType.name());
                if (SqlCommandType.INSERT == sqlCommandType || SqlCommandType.UPDATE == sqlCommandType) {
                    continue;
                } else {
                    break;
                }
            }
            if(arg instanceof Map) {
                //如果是map，有两种情况：（1）使用@Param多参数传入，由Mybatis包装成map。（2）原始传入Map
                Map<Object, Object> map = (Map<Object, Object>)arg;
                for (Object value : map.values()) {
                    setMatePropertie(value, sqlCommandType);
                }
            } else {
                setMatePropertie(arg, sqlCommandType);
            }
        }
        return invocation.proceed();

    }

    private void setMatePropertie(Object obj, SqlCommandType sqlCommandType) {
        String userName = null;
        try {
            userName = SecurityUtils.getUsername();
        } catch (CustomException ex) {
            userName = "system";
        }
        try {

            if (SqlCommandType.INSERT == sqlCommandType) {
                BeanUtil.setFieldValue(obj, "createBy", userName);
                BeanUtil.setFieldValue(obj, "createTime", LocalDateTime.now());
            }
            BeanUtil.setFieldValue(obj, "updateBy", userName);
            BeanUtil.setFieldValue(obj, "updateTime", LocalDateTime.now());
        } catch (Exception ex) {
            log.warn("设置元信息失败");
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
